package org.dizena.modules.wss.dao;

import org.dizena.base.dao.BaseDao;
import org.dizena.modules.wss.avo.ServerCount;
import org.dizena.modules.wss.bean.ServerClient;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;


@Repository
public class ServerClientDao extends BaseDao
{

    @Resource
    private MongoTemplate dao;

    public void save(ServerClient m)
    {
        dao.save(m);
    }

    public void deleteByClientId(String clientId)
    {
        Query query = keyIsVal("clientId", clientId);
        dao.remove(query, ServerClient.class);
    }

    public void deleteByServerId(String serverId)
    {
        Query query = keyIsVal("serverId", serverId);
        dao.remove(query, ServerClient.class);
    }

    public Long countServerClient(String serverId)
    {
        Query query = keyIsVal("serverId", serverId);
        return dao.count(query, ServerClient.class);
    }

    public ServerClient getServerClient(String clientId)
    {
        Query query = keyIsVal("clientId", clientId);
        return dao.findOne(query, ServerClient.class);
    }

    public List<ServerClient> getServerClientList(String serverId)
    {
        Query query = keyIsVal("serverId", serverId);
        return dao.find(query, ServerClient.class);
    }

    public List<ServerClient> queryAll()
    {
        return dao.findAll(ServerClient.class);
    }

    public List<ServerCount> countHost()
    {
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.group("serverId").count().as("connectCount"), Aggregation.project("connectCount").and("serverId").previousOperation());
        AggregationResults<ServerCount> aggregationResults = dao.aggregate(aggregation, ServerClient.class, ServerCount.class);
        return aggregationResults.getMappedResults();
    }

}